<?php
namespace Admin\Model;
use Think\Model;
class GoodsModel extends Model {
    //添加时调用create()方法允许接收的字段
    protected $insertFields = 'goods_name,shop_price,market_price,is_on_sale,goods_desc,brand_id';
    //修改时调用create()方法允许接收的字段
    protected $updateFields = 'id,goods_name,shop_price,market_price,is_on_sale,goods_desc,brand_id';
    //定义验证规则
    protected $_validate = array(
        array('goods_name','require','商品名称不能为空！',1),    //1表示必须验证，默认为0：表示存在的字段就验证
        array('market_price','currency','市场价格必须是货币类型！',1),  //因为表单是可以被客户端伪造的，所以配置
        array('shop_price','currency','本店价格必须是货币类型！',1),    //0有可能会不生效，比如客户端删掉一个字段
    );

    //这个方法在添加之前会自动被调用 --》 钩子函数
    //第一个参数：表单中即将要插入到数据库中的数据->数组
    //&按引用传递：函数内部要修改函数外部传进来的变量必须按引用传递，除非传递的是一个对象，因为对象默认是按引用传递的
    protected function _before_insert(&$data,$option) {
        /************ 处理LOGO **************/
        //判断有没有选择图片
        if($_FILES['logo']['error'] == 0) {
            $upload = new \Think\Upload();// 实例化上传类
            $upload->maxSize = 5 * 1024 * 1024 ;// 设置附件上传大小 不超过1M
            $upload->exts = array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
            $upload->rootPath = './Public/Uploads/'; // 设置附件上传根目录
            $upload->savePath = 'Goods/'; // 设置附件上传（子）目录
            // 上传文件
            $info = $upload->upload();
            if(!$info) {
            // 获取失败原因并保存到模型的error属性中，然后在控制器里会调用$model->getError()获取到错误信息并由控制器打印
                $this->error = $upload->getError();
                return false;
            }else{
                // 上传成功
                //dump($info);die;
                /************ 生成缩略图  **************/
                //先拼出原图的路径和名称
                $logo = $info['logo']['savepath'].$info['logo']['savename'];
                //拼出缩略图的路径和名称
                $mbiglogo = $info['logo']['savepath'].'mbig_'.$info['logo']['savename'];
                $biglogo = $info['logo']['savepath'].'big_'.$info['logo']['savename'];
                $midlogo = $info['logo']['savepath'].'mid_'.$info['logo']['savename'];
                $smlogo = $info['logo']['savepath'].'sm_'.$info['logo']['savename'];
                $image = new \Think\Image();
                //打开要生成缩略图的图片
                $image->open('./Public/Uploads/'.$logo);
                //生成缩略图
                $image->thumb(700,700)->save('./Public/Uploads/'.$mbiglogo);
                $image->thumb(350,350)->save('./Public/Uploads/'.$biglogo);
                $image->thumb(130,130)->save('./Public/Uploads/'.$midlogo);
                $image->thumb(50,50)->save('./Public/Uploads/'.$smlogo);
                /************ 把路径放到表单中 **************/
                $data['mbig_logo'] = $mbiglogo;
                $data['big_logo'] = $biglogo;
                $data['mid_logo'] = $midlogo;
                $data['sm_logo'] = $smlogo;
                $data['logo'] = $logo;
            }
        }
        /** function.php里面封装函数之后此回调函数if里面需要改成如下代码，去掉原来的
         *     $ret = uploadOne('logo','Goods',array(
                        array(700,700),
                        array(350,350),
                        array(130,130),
                        array(50,50),
                    ));
                $data['logo'] = $ret['image'][0];
                $data['mbig_logo'] = $ret['image'][1];
                $data['big_logo'] = $ret['image'][2];
                $data['mid_logo'] = $ret['image'][3];
                $data['sm_logo'] = $ret['image'][4];
         */


        //获取当前时间并添加到表单中这样就会插入到数据库中
        $data['addtime'] = date('Y-m-d H:i:s',time());
        //我们自己来过滤这个字段
        $data['goods_desc'] = removeXSS($_POST['goods_desc']);
    }

    protected function _before_update(&$data,$option) {
        $id = $option['where']['id'];     //获取要修改的商品ID
        /************ 处理LOGO **************/
        //判断有没有选择图片
        if($_FILES['logo']['error'] == 0) {
            $upload = new \Think\Upload();// 实例化上传类
            $upload->maxSize = 5 * 1024 * 1024 ;// 设置附件上传大小 不超过1M
            $upload->exts = array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
            $upload->rootPath = './Public/Uploads/'; // 设置附件上传根目录
            $upload->savePath = 'Goods/'; // 设置附件上传（子）目录
            // 上传文件
            $info = $upload->upload();
            if(!$info) {
                // 获取失败原因并保存到模型的error属性中，然后在控制器里会调用$model->getError()获取到错误信息并由控制器打印
                $this->error = $upload->getError();
                return false;
            }else{
                // 上传成功
                //dump($info);die;
                /************ 生成缩略图  **************/
                //先拼出原图的路径和名称
                $logo = $info['logo']['savepath'].$info['logo']['savename'];
                //拼出缩略图的路径和名称
                $mbiglogo = $info['logo']['savepath'].'mbig_'.$info['logo']['savename'];
                $biglogo = $info['logo']['savepath'].'big_'.$info['logo']['savename'];
                $midlogo = $info['logo']['savepath'].'mid_'.$info['logo']['savename'];
                $smlogo = $info['logo']['savepath'].'sm_'.$info['logo']['savename'];
                $image = new \Think\Image();
                //打开要生成缩略图的图片
                $image->open('./Public/Uploads/'.$logo);
                //生成缩略图
                $image->thumb(700,700)->save('./Public/Uploads/'.$mbiglogo);
                $image->thumb(350,350)->save('./Public/Uploads/'.$biglogo);
                $image->thumb(130,130)->save('./Public/Uploads/'.$midlogo);
                $image->thumb(50,50)->save('./Public/Uploads/'.$smlogo);
                /************ 把路径放到表单中 **************/
                $data['mbig_logo'] = $mbiglogo;
                $data['big_logo'] = $biglogo;
                $data['mid_logo'] = $midlogo;
                $data['sm_logo'] = $smlogo;
                $data['logo'] = $logo;
                /************* 删除原图 **************/
                //先查询出原来图片的路径
                $oldlogo = $this->field('logo,mbig_logo,big_logo,mid_logo,sm_logo')->find($id);
                //从硬盘上删除
                unlink('./Public/Uploads/'.$oldlogo['logo']);
                unlink('./Public/Uploads/'.$oldlogo['mbig_logo']);
                unlink('./Public/Uploads/'.$oldlogo['big_logo']);
                unlink('./Public/Uploads/'.$oldlogo['mid_logo']);
                unlink('./Public/Uploads/'.$oldlogo['sm_logo']);
            }
        }

        //我们自己来过滤这个字段
        $data['goods_desc'] = removeXSS($_POST['goods_desc']);
    }

    protected function _before_delete($option) {
        $id = $option['where']['id'];       //要删除的商品ID
        /************** 删除原来的图片 *************/
        //先找出要删除图片的路径
        $oldlogo = $this->field('logo,mbig_logo,big_logo,mid_logo,sm_logo')->find($id);
        //从硬盘上删除
        deleteImage($oldlogo);
    }

    /**
     * 商品添加之后就会调用这个方法，其中$data['id']就是新添加的商品的ID
     *
     */
    protected function _after_insert($data,$option) {
        $mp = I('post.member_price');
        $mpModel = D('member_price');
        foreach($mp as $k => $v) {
            $_v = (float)$v;
            //如果设置了会员价格就插入到表中
            if($_v > 0){
                $mpModel->add(array(
                    'goods_id'  =>  $data['id'],
                    'level_id'  =>  $k,
                    'price'     =>  $v
                ));
            }
        }
    }
    /**
     * 实现翻页、搜索、排序
     */
    public function search($perpage = 5) {
        /*************** 搜索 ******************/
        $where = array();   //空的where条件
        //商品名称
        $gn = I('get.gn');
        if($gn)
            $where['goods_name'] = array('like',"%$gn%");
        //商品品牌
        $brand_id = I('get.brand_id');
        if($brand_id)
            $where['brand_id'] = array('eq',$brand_id);
        //价格
        $fp = I('get.fp');
        $tp = I('get.tp');
        if($fp && $tp)
            $where['shop_price']  = array('between',array($fp,$tp));    //where shop_price between $fp and $tp
        elseif($fp)
            $where['shop_price']  = array('egt',$fp);           //where shop_price >= $fp
        elseif($tp)
            $where['shop_price']  = array('elt',$tp);          //where shop_price <= $tp
        //是否上架
        $ios = I('get.ios');
        if($ios)
            $where['is_on_sale']  = array('eq',$ios);           //where is_on_sale = $ios
        //添加时间
        $fa = I('get.fa');
        $ta = I('get.ta');
        if($fa && $ta)
            $where['addtime']  = array('between',array($fa,$ta));    //where addtime between $fp and $tp
        elseif($fa)
            $where['addtime']  = array('egt',$fa);           //where addtime >= $fp
        elseif($ta)
            $where['addtime']  = array('elt',$ta);          //where addtime <= $tp
        /*************** 排序 ******************/
        $orderby = 'id';        //默认的排序字段
        $orderway = 'desc';     //默认的排序方式
        $odby = I('get.odby');
        if($odby) {
            if($odby == 'id_asc')
                $orderway = 'asc';
            elseif($odby == 'price_desc')
                $orderby = 'shop_price';
            elseif($odby == 'price_asc') {
                $orderby = 'shop_price';
                $orderway = 'asc';
            }
        }
        /*************** 翻页 ******************/
        //取出总的记录数
        $count = $this->where($where)->count();
        //生成翻页类的对象
        $pageObj = new \Think\Page($count,$perpage);
        //设置样式
        $pageObj->setConfig('next','下一页');
        $pageObj->setConfig('prev','上一页');
        //获取翻页类的字符串
        $pageString = $pageObj->show();
        /************* 取某一页的数据 ************/
        $data = $this->order("$orderby $orderway")                          //排序
            ->field('a.*,b.logo')                                       //取字段
            ->alias('a')                                                    //取别名
            ->join('left join __BRAND__ b on a.brand_id = b.id')            //连表
            ->where($where)                                                 //搜索
            ->limit($pageObj->firstRow.','.$pageObj->listRows)              //翻页
            ->select();

        /************** 返回数据 ****************/
        return array(
            'page'  => $pageString,     //翻页字符串
            'data'  => $data            //数据
        );
    }
}
